package com.killer.controller;

import com.killer.service.FastDFSClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@RestController
@RequestMapping("fdfs")
public class FastDFSController {

    @Autowired
    private FastDFSClientService fastDFSClientService;

    @RequestMapping("/upload")
    public String uploadFile(MultipartFile file) throws IOException {
        return fastDFSClientService.uploadFile(file);
    }

    @RequestMapping("/download")
    public void download(@RequestParam("url") String url, HttpServletResponse response) throws Exception {
        byte[] bytes = fastDFSClientService.downloadFile(url);
        response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(url,"UTF-8"));
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }
}
